package de.playmee;

import java.io.IOException;
import java.io.InputStream;

import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.ParserConfigurationException;

import org.apache.http.HttpResponse;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.DefaultHttpClient;
import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;
import org.xml.sax.SAXException;

import android.util.Log;

public class XMLParser {

	private final static String TAG = "XMLParser";
	
	/**
	 * sends a HTTP request and parses the result (XML file) to a document
	 * 
	 * @param link
	 * @return document
	 * @throws IOException
	 * @throws SAXException
	 * @throws ParserConfigurationException
	 */
	public static Document getDocument(String link) throws SAXException, IOException, ParserConfigurationException {
		Log.i(TAG, "Sending http request...");
		HttpClient client = new DefaultHttpClient();
		HttpGet request = new HttpGet(link);
		
		Log.i(TAG, "Receiving http response...");
		HttpResponse response = client.execute(request);
		InputStream is = response.getEntity().getContent();

		Log.i(TAG, "Creating document...");
		DocumentBuilderFactory dbFactory = DocumentBuilderFactory.newInstance();
		DocumentBuilder dBuilder = dbFactory.newDocumentBuilder();
		Document doc = dBuilder.parse(is);
		doc.getDocumentElement().normalize();
		return doc;
	}
	
	/**
	 * parses a string with the current weather conditions
	 * 
	 * @param link
	 * @return current weather conditions
	 */
	public static String parseWeatherConditions(String link) {
		Log.i(TAG, link);
    	String res = "";  
        try {
    		Document doc = getDocument(link);
    		
            NodeList nodes = (NodeList) doc.getElementsByTagName("current_conditions");
            NodeList children = nodes.item(0).getChildNodes();
            
            for (int j = 0; j < children.getLength(); j++) {
            	Node child = children.item(j);
                if(child.getNodeName().equals("condition") && child.getNodeType() == Node.ELEMENT_NODE){
                	res = ((Element) child).getAttribute("data"); 
                	break;
                }
            }
 
        } catch (Exception e) {
        	Log.e(TAG, "Error parsing the weather conditions.");
            e.printStackTrace();
        }
        return res;
    }
	
	/*
	public static PlayList createPlayList(String link, Channel c, MusicHandler mf) throws IOException, ParserConfigurationException, SAXException{
		Log.i(TAG, "Start parsing XML document to get a playlist...");
		LinkedList<Long> r1 = new LinkedList<Long>();
		LinkedList<Long> r2 = new LinkedList<Long>();
		LinkedList<Long> r3 = new LinkedList<Long>();
		LinkedList<Long> r4 = new LinkedList<Long>();
				
		HttpClient client = new DefaultHttpClient();
		HttpGet request = new HttpGet(link);
		HttpResponse response = client.execute(request);
		InputStream is = response.getEntity().getContent();

		DocumentBuilderFactory dbFactory = DocumentBuilderFactory.newInstance();
		DocumentBuilder dBuilder = dbFactory.newDocumentBuilder();

		Document doc = dBuilder.parse(is);
		doc.getDocumentElement().normalize();
		
		Node getratings = doc.getElementsByTagName("ratings").item(0);
		Element e = (Element) getratings;
		
		Log.i(TAG, "Parsing ratings...");
		NodeList ratings = e.getElementsByTagName("rating");
		
		for(int i=0; i<ratings.getLength(); i++){
			Node n = ratings.item(i);
			Element cur = (Element) n;
			
			Log.i(TAG, "Parsing trackid...");
			Node curattr = cur.getElementsByTagName("id").item(0);
			//System.out.println("song "+i+": "+curattr.getTextContent()+"\n");
			Long curid = Long.parseLong(curattr.getTextContent());
			int counter = 0;
			
			Element h;
			
			try{
				Log.i(TAG, "Parsing moods...");
				Node m = cur.getElementsByTagName("moods").item(0);
				h = (Element) m;
				NodeList moods = h.getElementsByTagName("mood");
				
				for(int j=0; j<moods.getLength(); j++){
					curattr = moods.item(j);
					//System.out.println("\t mood "+j+": "+curattr.getTextContent()+"\n");
					Mood mood = Mood.valueOf(curattr.getTextContent());
					if(c.getMoods().contains(mood)){
						counter++;
						break;
					}
				}
			}catch(NullPointerException npe){
				Log.i(TAG, "No moods found...");
			}
			
			try{
				Log.i(TAG, "Parsing weather...");
				Node w = cur.getElementsByTagName("weathers").item(0);
				h = (Element) w;
				NodeList weathers = h.getElementsByTagName("weather");
				
				for(int j=0; j<weathers.getLength(); j++){
					curattr = weathers.item(j);
					//System.out.println("\t weather "+j+": "+curattr.getTextContent()+"\n");
					Weather.Condition weather = Weather.Condition.valueOf(curattr.getTextContent());
					if(c.getWeatherConditions().contains(weather)){
						counter++;
						break;
					}
				}
			}catch(NullPointerException npe){
				Log.i(TAG, "No weather found...");
			}
			
			try{
				Log.i(TAG, "Parsing seasons...");
				Node s = cur.getElementsByTagName("seasons").item(0);
				h = (Element) s;
				NodeList seasons = h.getElementsByTagName("season");
				
				for(int j=0; j<seasons.getLength(); j++){
					curattr = seasons.item(j);
					//System.out.println("\t season "+j+": "+curattr.getTextContent()+"\n");
					Season season = Season.valueOf(curattr.getTextContent());
					if(c.getSeasons().contains(season)){
						counter++;
						break;
					}
				}
			}catch(NullPointerException npe){
				Log.i(TAG, "No Seasons found...");
			}
			
			try{
				Log.i(TAG, "Parsing timesOfDay...");
				Node t = cur.getElementsByTagName("timesOfDay").item(0);
				h = (Element) t;
				NodeList timesofday = h.getElementsByTagName("timeOfDay");
				
				for(int j=0; j<timesofday.getLength(); j++){
					curattr = timesofday.item(j);
					//System.out.println("\t timeofday "+j+": "+curattr.getTextContent()+"\n");
					TimeOfDay time = TimeOfDay.valueOf(curattr.getTextContent());
					if(c.getTimesOfDay().contains(time)){
						counter++;
						break;
					}
				}
			}catch(NullPointerException npe){
				Log.i(TAG, "No timesOfDay found...");
			}
			
			if(counter==1){
				r1.add(curid);
			}else if(counter==2){
				r2.add(curid);
			}else if(counter==3){
				r3.add(curid);
			}else if(counter==4){
				r4.add(curid);
			}
		}
		
		Log.i(TAG, "Parsing finished!");
		
		LinkedList<Long> tracks = new LinkedList<Long>();
		
		int size = 0;
		int maxsize = 20;
		
		Log.i(TAG, "Find the best songs...");
		
		while(!r4.isEmpty() && size < maxsize){
			tracks.add(r4.pollFirst());
			size++;
		}
		
		while(!r3.isEmpty() && size < maxsize){
			tracks.add(r3.pollFirst());
			size++;
		}
		
		while(!r2.isEmpty() && size < maxsize){
			tracks.add(r2.pollFirst());
			size++;
		}
		
		while(!r1.isEmpty() && size < maxsize){
			tracks.add(r1.pollFirst());
			size++;
		}
		
		PlayList pl = new PlayList();
		
		Log.i(TAG, "Creating playlist...");
		
		for(Long i:tracks){
			int localID = mf.getLocalTrackPosition(i);
			if(localID == -1){
				continue;
			}
			Track t = mf.getTrack(localID);
			pl.appendTrack(t);
		}
		

		Log.i(TAG, "Playlist created!");
		
		return pl;
	}
	*/
}
